<template>
    <div class="common-list comp-companys" v-loading.fullscreen="loading">
        <div class="common-list__head">
            <el-input class="filter" v-model="filters.name" size="small" style="width: 320px" clearable placeholder="请输入" :readonly="loading" @change="search(true)">
                <span slot="prepend">企业/项目名称</span>
            </el-input>
            <el-select class="filter" v-model="filters.cityId" size="small" style="width: 160px" @change="search(true)">
                <el-option label="不限所在城市" :value="null"></el-option>
                <template v-for="data in citys">
                    <el-option :key="data.id" :label="data.name" :value="data.id" v-if="data.province.id === filters.provinceId"></el-option>
                </template>
            </el-select>
            <el-select class="filter" v-model="filters.countyId" size="small" style="width: 160px" @change="search(true)">
                <el-option label="不限所在县区" :value="null"></el-option>
                <template v-for="data in countys">
                    <el-option :key="data.id" :label="data.name" :value="data.id" v-if="data.city.id === filters.cityId"></el-option>
                </template>
            </el-select>
            <el-select class="filter" v-model="filters.tagId" size="small" style="width: 160px" @change="search(true)">
                <el-option label="不限所属分类" :value="null"></el-option>
                <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>
            </el-select>
            <!-- <el-select class="filter" v-model="filters.deptId" size="small" style="width: 240px" @change="search(true)">
                <el-option label="不限主管工作队" :value="null"></el-option>
                <el-option v-for="data in depts" :key="data.id" :label="data.name" :value="data.id"></el-option>
                <div class="el-select-dropdown__item" @click="chooseDept()">选择工作队</div>
            </el-select> -->
            <el-select class="filter" v-model="filters.status" size="small" style="width: 140px" @change="search(true)">
                <el-option label="不限审核状态" :value="null"></el-option>
                <el-option v-for="data in env.companyStatus" :key="data.id" :label="data.name" :value="data.value"></el-option>
            </el-select>
            <el-button class="filter" type="primary" size="small" @click="search()">查询</el-button>
            <el-button class="filter" type="plain" size="small" @click="reset(true)">重置</el-button>
        </div>
        <div class="common-list__nect">
            <slot name="head" :loading="loading" :filters="filters" :selects="selects"></slot>
        </div>
        <div class="common-list__body">
            <el-table ref="table" size="medium" height="100%" :data="list" @header-click="onTableHeaderClick" @row-click="onTableRowClick" @selection-change="onTableSelectionChange">
                <el-table-column type="selection" align="center" v-if="select"></el-table-column>
                <el-table-column label="企业/项目名称" min-width="12">
                    <template #default="scope">
                        <img style="float: left; margin-right: 10px; width: 40px; height: 40px" :src="scope.row.logo || require('../assets/company-avatar.png')" />
                        <a :href="'#/corp/company?companyId=' + scope.row.id" v-if="link && access('corp')">{{ scope.row.name }}</a>
                        <span v-else>{{ scope.row.name }}</span>
                        <div style="margin-left: 50px; color: #aaa">{{ scope.row.typeText }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="所在地址" min-width="8">
                    <template #default="scope">
                        <template v-if="scope.row.location.lng > 0 && scope.row.location.lat > 0">
                            <a :href="scope.row.location.link" target="_blank" @click.stop v-if="link">{{ scope.row.city.name + scope.row.county.name + scope.row.location.address }}</a>
                            <span v-else>{{ scope.row.city.name + scope.row.county.name + scope.row.location.address }}</span>
                        </template>
                        <span v-else>{{ scope.row.city.name + scope.row.county.name + scope.row.location.address }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="所属行业" min-width="6">
                    <template #default="scope">{{ scope.row.industry.id ? scope.row.industry.name : "-" }}</template>
                </el-table-column>
                <el-table-column label="所属分类" min-width="6">
                    <template #default="scope">{{ scope.row.tag.id ? scope.row.tag.name : "-" }}</template>
                </el-table-column>
<!--                <el-table-column label="主管工作队" min-width="8">-->
<!--                    <template #default="scope">-->
<!--                        <template v-if="scope.row.depts.length > 0">-->
<!--                            <div v-for="dept in scope.row.depts" :key="dept.id">{{ dept.name }}</div>-->
<!--                        </template>-->
<!--                        <span v-else>-</span>-->
<!--                    </template>-->
<!--                </el-table-column>-->
                <el-table-column label="最近走访" min-width="6">
                    <template #default="scope">
                        <template v-if="scope.row.attendances.length > 0">
                            <span>{{ scope.row.attendances[0].client.name }}</span>
                            <div style="color: #aaa">{{ scope.row.attendances[0].startAt }}</div>
                        </template>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="事项统计" min-width="4">
                    <template #default="scope">
                        <span>共 {{ scope.row.stats.ordersTotal }} 项</span>
                        <div style="color: #aaa">未办结 {{ scope.row.stats.ordersFinishedNotTotal }} 项</div>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" min-width="4">
                    <template #default="scope">
                        <span class="el-status--warning" v-if="scope.row.status === 'approving'"></span>
                        <span class="el-status--success" v-else-if="scope.row.status === 'approved'"></span>
                        <span class="el-status--danger" v-else-if="scope.row.status === 'unapproved'"></span>
                        <span>{{ scope.row.statusText }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" :width="160" v-if="$slots.body || $scopedSlots.body">
                    <template #default="scope">
                        <slot name="body" :loading="loading" :filters="filters" :data="scope.row" :selects="selects"></slot>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="common-list__foot" :class="{ 'common-list__foot--slot': $slots.foot || $scopedSlots.foot }">
            <el-pagination background layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 50, 100]" :page-size="filters.linage" :current-page="filters.page" :total="filters.total" @size-change="onTableLinageChange" @current-change="onTablePageChange"></el-pagination>
            <slot name="foot" :loading="loading" :filters="filters" :selects="selects"></slot>
        </div>
        <comp-dialog title="选择工作队" width="720px" height="80vh" ref="deptPicker">
            <comp-depts style="height: 100%" ref="deptPickerList" expanded>
                <template #body="scope">
                    <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="chooseDept('submit', scope.data)" v-if="scope.data.type === 'team' || scope.data.type === 'office'">选择</el-button>
                </template>
                <template #foot>
                    <el-button type="danger" size="small" icon="el-icon-close" @click="chooseDept('end')">放弃</el-button>
                </template>
            </comp-depts>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { object, array, string, int, session } from "../util";
    export default {
        name: "comp-companys",
        mixins: [mixin],
        props: {
            clientId: { type: String, default: null },
            select: { type: Boolean, default: false },
            link: { type: Boolean, default: false },
        },
        data: () => ({
            loading: false,
            filters: {
                ids: null,
                name: null,
                provinceId: "450000",
                cityId: null,
                tagId: null,
                deptId: null,
                clientId: null,
                status: null,
                linage: 10,
                page: 1,
                total: 0,
            },
            list: [],
            selects: [],
            citys: [],
            countys: [],
            tags: [],
            depts: [],
        }),
        methods: {
            reset(deep) {
                let data = deep ? {} : object(session([this.env.key, this.$options.name, "filters", this.$route.fullPath]));
                this.filters = Object.assign(this.$options.data().filters, data);
                this.depts = array(session([this.env.key, this.$options.name, "depts", this.$route.fullPath]));
                this.search(true);
            },
            validate() {
                let filters = this.filters;
                let citys = this.citys;
                let countys = this.countys;
                let tags = this.tags;
                let depts = this.depts;
                filters.ids = null;
                filters.cityId = string(() => citys.find((city) => city.id === filters.cityId && city.province.id === filters.provinceId).id) || null;
                filters.countyId = string(() => countys.find((county) => county.id === filters.countyId && county.city.id === filters.cityId).id) || null;
                filters.tagId = string(() => tags.find((tag) => tag.id === filters.tagId).id) || null;
                filters.deptId = string(() => depts.find((dept) => dept.id === filters.deptId).id) || null;
                filters.clientId = this.clientId;
                filters.total = Math.max(int(filters.total), 0);
                filters.linage = Math.max(int(filters.linage), 1);
                filters.page = Math.max(Math.min(int(filters.page), Math.ceil(filters.total / filters.linage)), 1);
                session([this.env.key, this.$options.name, "filters", this.$route.fullPath], filters);
                session([this.env.key, this.$options.name, "depts", this.$route.fullPath], depts);
            },
            onTableHeaderClick() {
                this.select && this.$refs.table.toggleAllSelection();
            },
            onTableRowClick(row) {
                this.select && this.$refs.table.toggleRowSelection(row);
            },
            onTableLinageChange(value) {
                this.filters.linage = value;
                this.search(true);
            },
            onTablePageChange(value) {
                this.filters.page = value;
                this.search(true);
            },
            onTableSelectionChange(selects) {
                this.filters.ids = selects.map((data) => data.id);
                this.selects = selects;
            },
            chooseDept(action, dept) {
                if (this.loading) return;
                let filters = this.filters;
                if (!action || action === "start") {
                    this.$refs.deptPicker.init();
                    this.$nextTick(() => this.$refs.deptPickerList.init());
                } else if (action === "submit") {
                    let index = this.depts.findIndex((target) => target.id === dept.id);
                    if (index > -1) this.depts.splice(index, 1);
                    filters.deptId = dept.id;
                    this.depts.push({ id: dept.id, name: dept.name });
                    this.chooseDept("end");
                    this.search(true);
                } else if (action === "end") {
                    this.$refs.deptPicker.close();
                }
            },
             search(clean) {
                if (this.loading) return;
                if (clean) this.list = [];
                if (clean) this.selects = [];
                let filters = this.filters;
                this.validate();
                this.loading = true;
                this.plugins.user.getCompanysother(filters).then((res) => {
                    this.loading = false;
                    this.list = [];
                    this.selects = [];
                    this.$nextTick(() => this.$refs.table.doLayout());
                    if (res.code === 0) {
                        let data = res.data;
                        // console.log(data);
                        if (data.page > 1 && data.list.length === 0) {
                            // console.log(1111);
                            filters.total = 0;
                            this.search();
                        } else {
                            // console.log(2222);
                            filters.total = data.total;
                            this.list = data.list;
                            this.validate();
                        }
                    } else {
                        filters.total = 0;
                        this.validate();
                        this.plugins.modal.toast("列表加载失败<br>" + res.code + "：" + res.msg, "error");
                    }
                });
            },
            init() {
                this.loading = true;
                this.plugins.user.call(async () => {
                    this.citys = this.plugins.user.citys;
                    this.countys = this.plugins.user.countys;
                    this.tags = this.tags.length > 0 ? this.tags : await this.plugins.user.getCompanyOfTags({ linage: 100, page: 1 }).then((res) => array(() => res.data.list));
                }).then(() => {
                    this.loading = false;
                    this.reset();
                });
            },
        },
    };
</script>

<style lang="scss">
    .comp-companys {
        overflow: hidden;
    }
</style>